<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import echarts from 'echarts';
require('echarts/theme/macarons'); // echarts theme
import resize from './mixins/resize';
import dayjs from 'dayjs';

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart',
    },
    width: {
      type: String,
      default: '100%',
    },
    height: {
      type: String,
      default: '350px',
    },
    autoResize: {
      type: Boolean,
      default: true,
    },
    chartData: {
      type: Array,
      required: true,
    },
    xData: {
      type: Array,
      required: true,
    },
    type: {
      type: Array,
      required: true,
    },
    color: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val);
      },
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons');
      this.setOptions(this.chartData);

      this.chart.on('click', (params) => {
        this.$emit('click-call-back', params.name);
      });
    },
    setOptions(chartData) {
      this.chart.setOption({
        color: ['#f4516c', '#ffa600'],
        grid: {
          left: 50,
          right: 50,
          bottom: 20,
          top: 30,
          containLabel: true,
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
          },
        },
        xAxis: {
          data: this.xData,
          boundaryGap: false,
          axisTick: {
            show: false,
          },
        },
        yAxis: {
          axisTick: {
            show: false,
          },
        },
        legend: {
          data: Object.keys(this.chartData),
        },
        series: Object.keys(this.chartData).map((name, index) => ({
          name,
          type: 'line',
          smooth: true,
          data: this.chartData[name],
          animationDuration: 2800,
          animationEasing: 'quadraticOut',
        })),
      });
    },
  },
};
</script>
